#ifndef __TEXTURE2D_H__
#define __TEXTURE2D_H__

#include <glad/glad.h>
#include <stb/stb_image.h>
#include <iostream>

class Image{
public:
    Image(const char *filename)
    {
        data = stbi_load(filename, &width, &height, &channel, 0);
        if(data == NULL) 
            std::cout << "Failed to load texture" << std::endl;
    }
    ~Image()
    {
        //this->Delete();
    }
    void Delete()
    {
        stbi_image_free(data);
        data = NULL;

    }
    int width, height, channel;
    unsigned char *data;
};


class Texture2D
{
public:
    Texture2D()
    {
        glGenTextures(1, &id);
    }
    Texture2D(GLuint id) : id(id) {}
    ~Texture2D()
    {
        //if(!id) this->Delete();
    }
    GLuint getID() const { return id;}
    void setID(GLuint id) { this->id = id; }
    void bind() const {glBindTexture(GL_TEXTURE_2D, id);}
    void unbind() const {glBindTexture(GL_TEXTURE_2D, 0);}
    void Delete() {glDeleteTextures(1, &id); id = 0;}
    void setImage(Image &image)
    {
        this->bind();
        GLenum type = image.channel == 4 ? GL_RGBA : GL_RGB;
        glTexImage2D(GL_TEXTURE_2D, 0, type, 
        image.width, image.height, 0, type, GL_UNSIGNED_BYTE, image.data);
        glGenerateMipmap(GL_TEXTURE_2D);
        this->unbind();
    }
    void active(int unit)
    {
        glActiveTexture(GL_TEXTURE0 + unit);
        this->bind();
    }
private:
    GLuint id;
};

#endif